<template>
  <div class="decommission-page">
    <!-- 查询表单 -->
    <el-card class="query-card" shadow="never">
      <el-form :model="queryForm" inline>
        <el-form-item label="水库名称">
          <el-input v-model="queryForm.reservoirName" placeholder="请输入水库名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="降等类型">
          <el-select v-model="queryForm.type" placeholder="请选择降等类型" clearable style="width: 150px">
            <el-option label="降等" value="downgrade" />
            <el-option label="报废" value="decommission" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="申请中" value="applying" />
            <el-option label="审核中" value="reviewing" />
            <el-option label="已批准" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请日期">
          <el-date-picker v-model="queryForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="operation-card" shadow="hover">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-button type="primary" plain :icon="Plus" @click="handleAdd">新增申请</el-button>
          <el-button type="danger" plain :icon="Delete" :disabled="!selectedRows.length" @click="handleBatchDelete">
            批量删除
          </el-button>
          <el-button type="success" plain :icon="Download" @click="handleExport">导出数据</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="code" label="申请编号" width="120" />
        <el-table-column prop="reservoirName" label="水库名称" width="150" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applicant" label="申请人" width="100" />
        <el-table-column prop="applyDate" label="申请日期" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="申请原因" min-width="200" show-overflow-tooltip />
        <el-table-column prop="reviewer" label="审核人" width="100" />
        <el-table-column prop="reviewDate" label="审核日期" width="120" />
        <el-table-column prop="completionDate" label="完成日期" width="120" />
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link :icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="info" link :icon="View" @click="handleView(row)">
              查看
            </el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <Pagination v-model:page="pagination.currentPage" v-model:limit="pagination.pageSize" :total="pagination.total"
          @pagination="handlePagination" />
      </div>
    </el-card>

    <!-- 表单弹窗 -->
    <DecommissionFormDialog v-model:visible="dialogVisible" :form-data="currentRow" :is-view="isView"
      @success="handleDialogSuccess" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Download, Edit, View } from '@element-plus/icons-vue'
import DecommissionFormDialog from './components/DecommissionFormDialog.vue'
import Pagination from '@/components/Pagination/index.vue'

// 查询表单
const queryForm = reactive({
  reservoirName: '',
  type: '',
  status: '',
  dateRange: []
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 弹窗相关
const dialogVisible = ref(false)
const currentRow = ref(null)
const isView = ref(false)

// 获取类型标签样式
const getTypeTagType = (type: string) => {
  const typeMap = {
    downgrade: 'warning',
    decommission: 'danger'
  }
  return typeMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type: string) => {
  const typeMap = {
    downgrade: '降等',
    decommission: '报废'
  }
  return typeMap[type] || type
}

// 获取状态标签样式
const getStatusTagType = (status: string) => {
  const statusMap = {
    applying: 'info',
    reviewing: 'warning',
    approved: 'success',
    rejected: 'danger',
    completed: 'success'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    applying: '申请中',
    reviewing: '审核中',
    approved: '已批准',
    rejected: '已拒绝',
    completed: '已完成'
  }
  return statusMap[status] || status
}

// 数据源与工具函数
const allData = ref<any[]>([])
const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
const randomChoice = <T>(arr: T[]) => arr[Math.floor(Math.random() * arr.length)]

const generateMockData = (count: number) => {
  const types = ['downgrade', 'decommission']
  const statuses = ['applying', 'reviewing', 'approved', 'rejected', 'completed']
  const reservoirs = ['青山水库', '白云水库', '龙湖水库', '梅岭水库', '溪口水库']
  const applicants = ['张三', '李四', '王五', '赵六', '钱七']
  const reviewers = ['审核员A', '审核员B', '审核员C']
  const departments = ['水利局', '水务公司', '水政科']
  const levels = ['一等', '二等', '三等', '四等']
  const today = new Date()
  const data: any[] = []
  for (let i = 1; i <= count; i++) {
    const apply = new Date(today.getTime() - randInt(0, 120) * 24 * 3600 * 1000)
    const reviewDelay = randInt(0, 10)
    const completeDelay = randInt(0, 20)
    const applyDate = `${apply.getFullYear()}-${String(apply.getMonth() + 1).padStart(2, '0')}-${String(apply.getDate()).padStart(2, '0')}`
    const reviewDate = `${apply.getFullYear()}-${String(apply.getMonth() + 1).padStart(2, '0')}-${String(apply.getDate() + reviewDelay).padStart(2, '0')}`
    const status = randomChoice(statuses)
    const completionDate = status === 'completed' ? `${apply.getFullYear()}-${String(apply.getMonth() + 1).padStart(2, '0')}-${String(apply.getDate() + completeDelay).padStart(2, '0')}` : ''
    const type = randomChoice(types)
    data.push({
      id: i,
      code: `DC${today.getFullYear()}${String(i).padStart(4, '0')}`,
      reservoirName: randomChoice(reservoirs),
      type,
      applicant: randomChoice(applicants),
      applyDate,
      status,
      reason: type === 'downgrade' ? '安全隐患导致降等申请' : '年久失修无修复价值',
      reviewer: randomChoice(reviewers),
      reviewDate,
      completionDate,
      phone: `138${String(randInt(10000000, 99999999))}`,
      department: randomChoice(departments),
      originalLevel: randomChoice(levels),
      targetLevel: type === 'downgrade' ? randomChoice(levels) : '报废',
      remark: ''
    })
  }
  return data
}

const applyFiltersAndPaginate = () => {
  let filtered = allData.value.slice()
  if (queryForm.reservoirName) {
    const kw = queryForm.reservoirName.trim()
    filtered = filtered.filter(item => String(item.reservoirName).includes(kw))
  }
  if (queryForm.type) {
    filtered = filtered.filter(item => item.type === queryForm.type)
  }
  if (queryForm.status) {
    filtered = filtered.filter(item => item.status === queryForm.status)
  }
  if (Array.isArray(queryForm.dateRange) && queryForm.dateRange.length === 2 && queryForm.dateRange[0] && queryForm.dateRange[1]) {
    const [start, end] = queryForm.dateRange as [string, string]
    const startTime = new Date(start).getTime()
    const endTime = new Date(end).getTime()
    filtered = filtered.filter(item => {
      const t = new Date(item.applyDate).getTime()
      return t >= startTime && t <= endTime
    })
  }
  pagination.total = filtered.length
  const startIndex = (pagination.currentPage - 1) * pagination.pageSize
  tableData.value = filtered.slice(startIndex, startIndex + pagination.pageSize)
}

// 获取降等报废列表（分页切片）
const fetchDecommissionList = async () => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    if (!allData.value.length) {
      allData.value = generateMockData(randInt(10, 50))
    }
    applyFiltersAndPaginate()
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 模拟API - 删除降等报废申请
const deleteDecommission = async (ids: number[]) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    allData.value = allData.value.filter((item: any) => !ids.includes(item.id))
    ElMessage.success('删除成功')
    applyFiltersAndPaginate()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 模拟API - 导出数据
const exportDecommission = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 查询
const handleQuery = () => {
  pagination.currentPage = 1
  applyFiltersAndPaginate()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    reservoirName: '',
    type: '',
    status: '',
    dateRange: []
  })
  handleQuery()
}

// 新增
const handleAdd = () => {
  currentRow.value = null
  isView.value = false
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  currentRow.value = { ...row }
  isView.value = false
  dialogVisible.value = true
}

// 查看
const handleView = (row: any) => {
  currentRow.value = { ...row }
  isView.value = true
  dialogVisible.value = true
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除这条申请记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteDecommission([row.id])
  })
}

// 批量删除
const handleBatchDelete = () => {
  const ids = selectedRows.value.map((row: any) => row.id)
  ElMessageBox.confirm(`确定要删除选中的 ${ids.length} 条申请记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteDecommission(ids)
  })
}

// 导出
const handleExport = () => {
  exportDecommission()
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 分页处理
const handlePagination = (page: any) => {
  pagination.currentPage = page.page
  pagination.pageSize = page.limit
  applyFiltersAndPaginate()
}

// 弹窗成功回调
const handleDialogSuccess = () => {
  fetchDecommissionList()
}

// 初始化
onMounted(() => {
  fetchDecommissionList()
})
</script>

<style scoped>
.decommission-page {
  padding: 20px;
}

.query-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>